package com.hrbxlh.util;


import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 通过java获取图片的宽和高
 * @author sy
 * 2018-7-26
 */
public class ImageTools {

    /**
     * 获取图片宽度
     * @param file  图片文件
     * @return 宽度
     */
    public static double getImgWidth(File file) throws IOException {
        InputStream is = null;
        BufferedImage src = null;
        double ret = -1;
        try {
            is = new FileInputStream(file);
            src = ImageIO.read(is);
            ret = src.getWidth(null); // 得到源图宽

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            is.close();
        }
        return ret;
    }


    public static double getOnlineImgHeight(MultipartFile file){
        BufferedImage sourceImg = null;
        try {
            sourceImg = ImageIO.read(file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sourceImg.getHeight();
    }

    public static double getOnlineImgWidth(MultipartFile file){
        BufferedImage sourceImg = null;
        try {
            sourceImg = ImageIO.read(file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sourceImg.getWidth();
    }

   /* public static void main(String[] args) throws IOException {
        File f = new File("C:\\Users\\Administrator\\Desktop\\logo2.png");
        double width = getImgWidth(f);
        double height = getImgHeight(f);
        System.out.println("长："+getImgWidth(f));
        System.out.println("高："+getImgHeight(f));
        if(height<52){
            //说明上传的图片大小符合规则，不需要进行压缩
        }
        //将高给为52，则对应的长度为
        double finalWidth = (52*width)/height;
        finalWidth = (double)Math.round(finalWidth*100)/100;//保留两位小数
        //开始按高进行压缩
        Thumbnails.Builder<File> builder = Thumbnails.of(f);
        builder.height(52).toFile(f);//按高度进行压缩
        //按高度压缩后在查询压缩后的图片宽
        double widthThree = ImageTools.getImgWidth(f);
        if(widthThree<260){
            //说明这个压缩比例符合，可以直接返回
        }
        //说明按高压缩完后，宽度不符合，则开始按宽度进行压缩
        //将宽给260，对应的高度应该为
        double finalHeight =(260*height)/width;
        finalHeight = (double)Math.round(finalHeight*100)/100;//保留两位小数
    }*/
}
